package com.sniper.springmvc.action.admin;

import com.sniper.springmvc.data.DataValues;
import com.sniper.springmvc.mybatis.service.impl.LoginLogService;
import com.sniper.springmvc.searchUtil.ChannelSearch;
import com.sniper.springmvc.utils.PageUtil;
import com.sniper.springmvc.utils.ParamsToHtml;
import com.sniper.springmvc.utils.UserDetailsUtils;
import com.sniper.springmvc.utils.ValidateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("${adminPath}/admin-logs")
public class AdminLogsController extends AdminBaseController {


    @Resource
    private LoginLogService loginLogService;


    /**
     * 登录日志
     *
     * @param map
     * @param channelSearch
     * @return
     */
    @RequiresPermissions("admin:logs:login")
    @RequestMapping("login")
    public String login(Map<String, Object> map, ChannelSearch channelSearch) {

        map.put("sniperUrl", "/admin-logs/delete");

        ParamsToHtml toHtml = new ParamsToHtml();

        Map<String, Object> where = new HashMap<>();

        UserDetailsUtils detailsUtils = new UserDetailsUtils();
        if (detailsUtils.hasRole(DataValues.ROLE_ADMIN)) {
            where.put("name", detailsUtils.getPrincipal());
        }
        if (ValidateUtil.isValid(channelSearch.getName())) {
            where.put("name", channelSearch.getName());
        }
        where.put("order", "stime desc");
        PageUtil page = loginLogService.page(request, 50, where);

        map.put("page", page);
        map.put("sniperMenu", toHtml);
        return forward("/admin/admin-logs/login.ftl");
    }

    @RequiresPermissions("admin:logs:delete")
    @ResponseBody
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public Map<String, Object> delete(@RequestParam("delid") String[] delid,
                                      @RequestParam("menuType") String menuType,
                                      @RequestParam("menuValue") String menuValue) {

        Map<String, Object> ajaxResult = new HashMap<>();
        switch (menuType) {
            case "delete":
                try {
                    loginLogService.batchDelete("delete", delid);
                    ajaxResult.put("code", 1);
                    ajaxResult.put("msg", "success");
                } catch (Exception e) {
                    ajaxResult.put("code", -1);
                    ajaxResult.put("msg", "删除失败");
                }
                break;

            default:
                break;
        }
        return ajaxResult;
    }
}